package com.ktgj.customer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.dto.RefuseCardCardDataDTO;
import com.ktgj.customer.domain.dto.RefuseCardCustomerDataDTO;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.IFinanceOrderRefundmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.service.IReturncardService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 退卡申请Service业务层处理
 *
 * @author ruoyi
 * @date 2021-09-15
 */
@Service
@Transactional
public class ReturncardServiceImpl implements IReturncardService {
    @Autowired
    private ReturncardMapper returncardMapper;
    @Autowired
    private CustomerCardMapper customerCardMapper;
    @Autowired
    private CustomerRightdetailMapper customerRightdetailMapper;
    //    @Autowired
//    private DepositBusinessMapper depositBusinessMapper;
    @Autowired
    private IFinanceOrderRefundmentService financeOrderRefundmentService;
    @Autowired
    private BusinessRefundMapper businessRefundMapper;
    @Autowired
    private BusinessOrderSubMapper businessOrderSubMapper;
    @Autowired
    private BusinessOrderMapper businessOrderMapper;
    @Autowired
    private CustomerCardRecordMapper customerCardRecordMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private EmployeeMapper employeeMapper;
    /**
     * 查询退卡申请
     *
     * @param orderId 退卡申请ID
     * @return 退卡申请
     */
    @Override
    public Returncard selectReturncardById(Long orderId) {
        return returncardMapper.selectReturncardById(orderId);
    }

    /**
     * 查询退卡申请列表
     *
     * @param returncard 退卡申请
     * @return 退卡申请
     */
    @Override
    public List<Returncard> selectReturncardList(Returncard returncard) {
        return returncardMapper.selectReturncardList(returncard);
    }

    /**
     * 新增退卡申请
     *
     * @param returncard 退卡申请
     * @return 结果
     */
    @Override
    public int insertReturncard(Returncard returncard) {
        return returncardMapper.insertReturncard(returncard);
    }

    /**
     * 修改退卡申请
     *
     * @param returncard 退卡申请
     * @return 结果
     */
    @Override
    public int updateReturncard(Returncard returncard) {
        return returncardMapper.updateReturncard(returncard);
    }

    /**
     * 批量删除退卡申请
     *
     * @param orderIds 需要删除的退卡申请ID
     * @return 结果
     */
    @Override
    public int deleteReturncardByIds(Long[] orderIds) {
        return returncardMapper.deleteReturncardByIds(orderIds);
    }

    /**
     * 删除退卡申请信息
     *
     * @param orderId 退卡申请ID
     * @return 结果
     */
    @Override
    public int deleteReturncardById(Long orderId) {
        return returncardMapper.deleteReturncardById(orderId);
    }

    //申请退卡
    @Override
    public int applyRefund(Returncard returncard)
    {
        Employee employee = employeeMapper.selectEmployeeById(returncard.getCreatepersonid());
        if (employee != null)
        {
            Department department =  departmentMapper.selectDepartmentById(employee.getDeptId());
            returncard.setReturncarddeptId(department.getDeptId());
            returncard.setReturnCardDeptName(department.getDeptName());
        }
        Gson gson = new Gson();
        returncard.setRemarks(gson.toJson(returncard.getRemarkList()));
        returncard.setIshasguaranteemoney(returncard.getPenaltguaranteemoney() != null && returncard.getPenaltguaranteemoney().compareTo(new BigDecimal(0)) == 1 ? CustomerConstants.yes.getValue() : CustomerConstants.no.getValue());
        returncard.setCreateTime(new Date());
        if (returncard.getCardCode() != null && !StringHelper.isNullOrEmpty(returncard.getCardCode()))
        {
            //冻结会员卡
            customerCardMapper.updateCustomerCard(new CustomerCard(returncard.getCardId(), CustomerConstants.frozen.getValue()));
            //冻结会员卡下的权益
            customerRightdetailMapper.updateCustomerRightdetailToFrozen(returncard.getCardId());
        }
        int i = returncardMapper.insertReturncard(returncard);
        //todo 保险待整合
        return i;
    }

    //退卡申请未通过
    @Override
    public int refuseRefund(Long returnCardId) {
        Returncard returncard = returncardMapper.selectReturncardById(returnCardId);
        int i = returncardMapper.updateReturncard(new Returncard(returncard.getOrderId(), null, CustomerConstants.refuseRefund.getValue()));
        if (returncard.getCardCode()!= null && !StringHelper.isNullOrEmpty(returncard.getCardCode()))
        {
            //解冻会员卡
            customerCardMapper.updateCustomerCard(new CustomerCard(returncard.getCardId(), CustomerConstants.valid.getValue()));
            //解冻会员卡下的权益
            customerRightdetailMapper.updateCustomerRightdetailTowardFrozen(returncard.getCardId());
        }
        //todo 保险待整合
        return i;
    }

    //退卡申请通过 //todo 好几张表的操作员工都应该填写哪个员工
    @Override
    public int refundApproved(Long returnCardId) throws Exception {
        Returncard returncard = returncardMapper.selectReturncardById(returnCardId);
        int i = returncardMapper.updateReturncard(new Returncard(returncard.getOrderId(), new Date(), CustomerConstants.refundApproved.getValue()));
        BusinessOrder businessOrder = null;
        if (returncard.getCardCode()!= null && !StringHelper.isNullOrEmpty(returncard.getCardCode()))
        {
            //作废会员卡
            customerCardMapper.updateCustomerCard(new CustomerCard(returncard.getCardId(), CustomerConstants.refunds.getValue()));
            //作废会员卡下的权益
            customerRightdetailMapper.updateCustomerRightdetailToRefunds(returncard.getCardId());
            businessOrder = businessOrderMapper.selectCustomerIdByCard(returncard.getCardId());
            businessOrderSubMapper.updateWhetherRefund(returncard.getCardId());
        }else
        {
            CustomerCardRecord customerCardRecord = customerCardRecordMapper.selectCustomerCardRecordById(returncard.getCardRecordId());
            if (customerCardRecord!=null)
            {
                businessOrder = businessOrderMapper.selectBusinessOrderByOrderId(customerCardRecord.getOrderId());
                BusinessOrderSub businessOrderSub = new BusinessOrderSub();
                businessOrderSub.setOrderId(businessOrder.getOrderId());
                businessOrderSub.setWhetherRefund("yes");
                businessOrderSubMapper.updateBusinessOrderSub(businessOrderSub);
                if (customerCardRecord != null)
                {
                    customerCardRecord.setIssyn(CustomerConstants.refunds.getValue());
                    customerCardRecordMapper.updateCustomerCardRecord(customerCardRecord);
                }
            }
        }
        //todo 保险待整合

        BigDecimal refunddeposit = returncard.getRefunddeposit() == null ? refunddeposit = new BigDecimal(0) : returncard.getRefunddeposit();
        BigDecimal refundcash = returncard.getRefundcash() == null ? refunddeposit = new BigDecimal(0) : returncard.getRefundcash();

        //创建退款订单
        BusinessRefund businessRefund = new BusinessRefund();
        businessRefund.setRefundCode(businessOrder.getOrdernum());
        businessRefund.setCustomerId(businessOrder.getCustomerId());//会员id
        businessRefund.setPenaltguaranteemoney(returncard.getPenaltguaranteemoney());//会员承担保费金额（扣会员保费）
        businessRefund.setEmployeeguaranteemoney(returncard.getEmployeeguaranteemoney());//员工承担保费金额
        businessRefund.setPartnerviphallnum(returncard.getPartnerviphallnum());//合作厅使用次数
        businessRefund.setVipchannelnum(returncard.getVipchannelnum());//安检使用次数
        businessRefund.setSalesmoney(returncard.getSalesmoney());//促销活动费用
        //退款完成时间
        //子订单ID
        //businessRefund.setRefundWay(returncard.getRefundmethod());//退款方式？？？？？？
        //退续费年限
        businessRefund.setDepreciationPrice(returncard.getDepreciationmoney());//折旧费
        businessRefund.setRefundPrice(refunddeposit.add(refundcash));//实退金额（预留款+在线支付）
        businessRefund.setRefundReserved(refunddeposit);//应退预留款
        //积分、积分折现

        String remarks = null;
        if (returncard.getRemarks() != null && returncard.getRemarkList()!=null && returncard.getRemarkList().size() > 0){
            for (int j = 0; j < returncard.getRemarkList().size(); j++) {
                if (j == 0){
                    remarks = returncard.getRemarkList().get(i);
                }
                else {
                    remarks = remarks + "," + returncard.getRemarkList().get(i);
                }
            }
        }
        businessRefund.setRemark(remarks);//退款原因
        businessRefund.setCreateTime(new Date());//创建时间
        businessRefund.setRefundState(CustomerConstants.applyRefund.getValue());//退款状态
        businessRefund.setEmployeeId(returncard.getCreatepersonid());//操作员工
        businessRefund.setBankcardHolder(returncard.getBankusername());//银行卡持卡人
        businessRefund.setBankcardId(returncard.getRemittanceaccount());//银行卡号
        businessRefund.setBankcardOpenCity(returncard.getSubbranchbank());//开户行
        businessRefund.setRefundBank(returncard.getBankname());//退款银行
        businessRefund.setPayType(returncard.getRefundmethod());//退款方式类型（预留款、线下打款）
        businessRefund.setSourceway(60l);
        //支付时间
        businessRefundMapper.insertBusinessRefund(businessRefund);

        /*DepositBusiness depositBusiness = new DepositBusiness();
        depositBusiness.setState(EmHelper.Audit.NotReviewed.getValue());
        depositBusiness.setCustomerId(customerId);//会员id
        depositBusiness.setDetailamount(refunddeposit);//明细金额
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            depositBusiness.setCreateTime(format.parse(format.format(new Date())));
        } catch (Exception e){
            throw new Exception("日期转换错误");
        }

        if (!refunddeposit.equals(new BigDecimal(0))) {
            depositBusiness.setBusinessType(CustomerConstants.refundsCard.getValue());//订单来源类型
            depositBusiness.setOperatorId(returncard.getCreatepersonid());//操作员id
            depositBusiness.setChangetype(1L);//方向（1增2减）
            depositBusiness.setOrderId(businessRefund.getRefundId());//订单id
        }
        if (returncard.getRefundmethod().equals(CustomerConstants.cash.getValue())) {
            //todo 退现金操作

            if (!refunddeposit.equals(new BigDecimal(0)))
                depositBusinessMapper.insertDepositBusiness(depositBusiness);
        } else {
            depositBusiness.setDetailamount(refunddeposit.add(refundcash));
            depositBusinessMapper.insertDepositBusiness(depositBusiness);
        }*/

        //向财务提交需要退款的记录
        FinanceOrderRefundment financeOrderRefundment = new FinanceOrderRefundment();
        financeOrderRefundment.setOrderTypeId(new Long(com.ktgj.common.core.constant.FinanceOrderRefundment.customer.getValue()));
        financeOrderRefundment.setCustomerId(businessOrder.getCustomerId());
        switch (returncard.getRefundmethod()) {
            case "0":
                financeOrderRefundment.setRefundmentType(new Long(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
                break;
            case "1":
                financeOrderRefundment.setRefundmentType(new Long(com.ktgj.common.core.constant.FinanceOrderRefundment.depositBusiness.getValue()));
                break;
            case "2":
                financeOrderRefundment.setRefundmentType(new Long(com.ktgj.common.core.constant.FinanceOrderRefundment.bankCard.getValue()));
                break;
        }
        financeOrderRefundment.setOrderId(businessRefund.getRefundCode());
        String remark = null;
        if (returncard.getRemarks() != null && returncard.getRemarkList()!=null && returncard.getRemarkList().size() > 0){
            for (int j = 0; j < returncard.getRemarkList().size(); j++) {
                if (j == 0){
                    remark = returncard.getRemarkList().get(i);
                }
                else {
                    remark = remark + "," + returncard.getRemarkList().get(i);
                }
            }
        }
        financeOrderRefundment.setRefundmentDesc(remark);
        financeOrderRefundment.setApplyTime(returncard.getCreateTime());
        financeOrderRefundment.setEmployeeIdCreate(returncard.getCreatepersonid());
        financeOrderRefundment.setEmployeeIdApply(returncard.getCreatepersonid());
        financeOrderRefundment.setCardNo(returncard.getRemittanceaccount());
        financeOrderRefundment.setCardOwner(returncard.getBankusername());
        financeOrderRefundment.setBankCity(returncard.getSubbranchbank());
        financeOrderRefundment.setBankTypeId(returncard.getBankname());
        financeOrderRefundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
        financeOrderRefundment.setSerialnumber(businessOrder.getPartyPayNum());

        if (returncard.getRefundcash() != null && returncard.getRefundcash().doubleValue() != 0.00) {
            financeOrderRefundment.setRefundmentAmount(returncard.getRefundcash());
            financeOrderRefundmentService.insertFinanceOrderRefundment(financeOrderRefundment);
        }
        if (returncard.getRefunddeposit() != null && returncard.getRefunddeposit().doubleValue() != 0.00) {
            financeOrderRefundment.setRefundmentAmount(returncard.getRefunddeposit());
            financeOrderRefundment.setRefundmentType(new Long(com.ktgj.common.core.constant.FinanceOrderRefundment.depositBusiness.getValue()));
            financeOrderRefundmentService.insertFinanceOrderRefundment(financeOrderRefundment);
        }

        return i;
    }

    @Override
    public RefuseCardCustomerDataDTO queryRefuseCardData(Long customerId, String cardCode, Long cardId)
    {
        CustomerCardRecord queryCardRecord = new CustomerCardRecord();
        queryCardRecord.setCardId(cardId);
        queryCardRecord.setCustormerId(customerId);
        queryCardRecord.setIssyn(CustomerConstants.unexecuted.getValue());
        List<Department> lstDepartment = departmentMapper.selectDepartmentByList();
        Employee employee = new Employee();
        List<Employee> lstEmployee = employeeMapper.selectEmployeeList(employee);
        List<CustomerCardRecord> lstCardRecord = customerCardRecordMapper.selectCustomerCardRecordList(queryCardRecord);
        RefuseCardCustomerDataDTO refuseCardCustomerDataDTO = returncardMapper.queryRefuseCardData(customerId, cardCode);
        if (refuseCardCustomerDataDTO != null)
            for (RefuseCardCardDataDTO item : refuseCardCustomerDataDTO.getRefuseCardCardDataDTOS())
            {
                CustomerRightdetail customerRightdetail = customerRightdetailMapper.selectGuaranteeByCustomerCardId(item.getCardId());
                if (customerRightdetail != null)
                    if (customerRightdetail.getRightdetailState().equals(CustomerConstants.unexecuted.getValue()))
                        item.setGuarantee(false);
                    else
                        item.setGuarantee(true);
                else
                    item.setGuarantee(false);


                long diff = item.getInvalidDate().getTime() - new Date().getTime();
                long diffDays = diff / (24l * 60l * 60l * 1000l) % 365l;
                long diffYears = diff / (365l * 24l * 60l * 60l * 1000l);
                StringBuffer stringBuffer = new StringBuffer();
                if (diffYears > 0)

                    stringBuffer.append(diffYears + "年");
                stringBuffer.append(diffDays + "天");
                item.setInvalidDateDetail(stringBuffer.toString());
            }
        else
            refuseCardCustomerDataDTO = new RefuseCardCustomerDataDTO();

        if (lstCardRecord.size() > 0)
        {
            for (CustomerCardRecord customerCardRecord : lstCardRecord)
            {
                Department department = lstDepartment.stream().filter(item -> item.getDeptId().equals(customerCardRecord.getCardsolddeptid())).findFirst().orElse(null);
                if (department != null)
                {
                    customerCardRecord.setCardSoldDeptName(department.getDeptName());
                }
                Employee queryEmployee = lstEmployee.stream().filter(item -> item.getEmployeeId().equals(customerCardRecord.getCardsoldemployeeid())).findFirst().orElse(null);
                if (queryEmployee != null)
                {
                    customerCardRecord.setCardSoldEmployeeName(queryEmployee.getEmployeeName());
                }
            }
            refuseCardCustomerDataDTO.getLstCardRecord().addAll(lstCardRecord);
        }
        return refuseCardCustomerDataDTO;
    }


}
